﻿using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML.Drawing
{
    [XmlRoot("graphic", Namespace = Constants.Graphic)]
    public class Graphic : XmlSerializable
    {
        [XmlElement("graphicData", Namespace = Constants.Graphic)]
        public GraphicData Data { get; set; }

        public Graphic() { }
    }

    [XmlRoot("graphicData", Namespace = Constants.Graphic)]
    public class GraphicData : XmlSerializable
    {
        [Optional]
        [XmlAttribute("uri", Form = XmlSchemaForm.Qualified)]
        public string Uri { get; set; }

        [XmlElement("")]
        public object DrawingElement { get; set; }

        public GraphicData() { }

        public override void ReadXml(System.Xml.XmlReader reader)
        {
            if (reader.HasAttributes)
            {
                this.Uri = reader.GetAttribute(0);
            }

            reader.Read();
            while (reader.NodeType == System.Xml.XmlNodeType.Whitespace)
                reader.Read();

            var assembly = Assembly.Load("DocumentFormat.OpenXml.Lite.DrawingML");
            var type = assembly.GetTypes().FirstOrDefault(
                t => t.GetCustomAttributes(typeof(XmlRootAttribute), false).Length > 0
                && (t.GetCustomAttributes(typeof(XmlRootAttribute), false)[0]
                as XmlRootAttribute).ElementName == reader.LocalName);
            if (type != null)
            {
                DrawingElement = assembly.CreateInstance(type.ToString());
                (DrawingElement as XmlSerializable).ReadXml(reader);
            }
        }
    }
}
